package pixelwaks.ctrl.impl;

import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;

import common.ctrl.IObserver;
import common.gui.IViewable;

import pixelwaks.core.impl.Game;
import pixelwaks.core.impl.Player;
import pixelwaks.core.impl.Projectile;
import pixelwaks.ctrl.ControlFactory;

public class ShootCtrl extends KeyAdapter implements IObserver {

	
	private List<IViewable> list = new ArrayList<IViewable>();
	private boolean spacePressed = false;
	
	@Override
	public void keyPressed(KeyEvent e) {
		//Invoked when a key has been pressed.
		int key = e.getKeyCode();
		boolean shoot = false;

		if(Game.lock.tryAcquire()) {
			PlayerCtrl pc = (PlayerCtrl) ControlFactory.getObserver(ControlFactory.PLAYER_CTRL);
			if(key == KeyEvent.VK_LEFT && !spacePressed)
				pc.aimLeft();

			else if(key == KeyEvent.VK_RIGHT && !spacePressed)
				pc.aimRight();

			else if(key == KeyEvent.VK_SPACE) {
				spacePressed = true;
				if(!pc.changeChargeStrength() && Game.getInstance().getCurrentPlayer().getCurrentWeapon().getNumberOfShots() != 0) {
					shoot = true;
					Game.lock.release();
					shoot();			
				}
			}
			
			for(IViewable iv : list) 
				iv.updateView(null);			
			
			if(!shoot)
				Game.lock.release();
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {

		if(Game.lock.tryAcquire()) {
			Game.lock.release();
			//Invoked when a key has been released. 
			if(e.getKeyCode() == KeyEvent.VK_SPACE)
				if(Game.getInstance().getCurrentPlayer().getCurrentWeapon().getNumberOfShots() != 0)
					shoot();
		}
	}
	
	private void shoot() {
		
		spacePressed = false;
		WeaponCtrl wctrl = (WeaponCtrl) ControlFactory.getObserver(ControlFactory.WEAPON_CTRL);
		wctrl.decreaseAmmo();
		Player current = Game.getInstance().getCurrentPlayer();
		/*
		 * Find the place where the barrel is anchored
		 */
		int initX = current.getPosition().x + current.getBody().getWidth() / 2;
		int initY = current.getPosition().y - Player.BARREL_OFFSET;
		
		/*
		 * Find Point where the projectile will be created
		 */
		int x = (int) (initX + (Math.cos(current.getBarrelAngle()) * current.getBarrel().getHeight()));
		int y = (int) (initY - (Math.sin(current.getBarrelAngle()) * current.getBarrel().getHeight()));
		
		int strength = current.getChargeStrength();
		int angle = (int) current.getDegrees();
		
		Projectile proj = (Projectile) Game.getInstance().getProjectile();
		proj.setStartPosition(new Point(x,y));
		proj.setCurrentPosition(new Point(x,y));
		proj.setAngle(angle);
		proj.setVelocity(strength);
		proj.setImage(current.getCurrentWeapon().getImage());
		
		ProjectileCtrl pctrl = 
			(ProjectileCtrl) ControlFactory.getObserver(ControlFactory.PROJECTILE_CTRL);
		pctrl.startAnimation(proj);
		
		PlayerCtrl pc = (PlayerCtrl) ControlFactory.getObserver(ControlFactory.PLAYER_CTRL);
		pc.resetChargeStrength();
	}

	@Override
	public void addView(IViewable iv) {
		list.add(iv);
		
	}

}
